import process from 'node:process';
import { URL, fileURLToPath } from 'node:url';
import { defineConfig, loadEnv } from 'vite';
import { setupVitePlugins } from './build/plugins';
import { getBuildTime } from './build/config';

export default defineConfig(configEnv => {
  const viteEnv = loadEnv(configEnv.mode, process.cwd()) as unknown as any;
  const buildTime = getBuildTime();

  return {
    base: './',
    resolve: {
      alias: {
        '~': fileURLToPath(new URL('./', import.meta.url)),
        '@': fileURLToPath(new URL('./src', import.meta.url))
      }
    },
    css: {
      preprocessorOptions: {
        scss: {
          additionalData: `@use "./src/styles/global.scss" as *;`
        }
      }
    },
    plugins: setupVitePlugins(viteEnv, buildTime),
    define: {
      BUILD_TIME: JSON.stringify(buildTime)
    },
    server: {
      host: '0.0.0.0',
      port: 8000,
      open: true,
      cors: true,
      proxy: {
        '/xxxx/': {
          target: 'https://xxxx',
          ws: false,
          changeOrigin: true,
          rewrite: (path) => path.replace(/^\/xxxx/, ''),
        },
      },
      fs: {
        cachedChecks: false
      }
    },
    preview: {
      port: 9725
    },
    build: {
      reportCompressedSize: false,
      sourcemap: false,
      target: 'es2015',
      commonjsOptions: {
        ignoreTryCatch: false
      },
      minify: 'terser',
      terserOptions: {
        compress: {
          drop_console: configEnv.mode == 'production' && viteEnv.VITE_PROD_CONSOLE != 'Y' ? ['log', 'info'] : false,
          drop_debugger: true,
        },
      },
    }
  };
});
